using IQIGame.Onigao.GamePlay;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(UnitEffectClip))]
public class UnitEffectClipEditor : Editor
{
    UnitEffectClip postProcessClip;
    GameObject templateGo;
    Color gColor = new Color(0.7f, 0.7f, 0.7f, 1f);

    private void OnEnable()
    {
        postProcessClip = target as UnitEffectClip;
        templateGo = postProcessClip.InstanceGo;
    }

    private void OnDestroy()
    {
        //GameObject.DestroyImmediate(templateGo);
    }

    public override void OnInspectorGUI()
    {
        if (Application.isPlaying)
        {
            // 在选中特效轨道启动游戏时，持续进行后续操作会造成序列化的gameobject丢失，在这里阻断一下
            base.OnInspectorGUI();
            return;
        }
        
        serializedObject.Update();

        var color = GUI.color;
        GUI.color = gColor;
        EditorGUILayout.LabelField("Full Path : ", postProcessClip.effectPath);
        EditorGUILayout.LabelField("EffectName : ", postProcessClip.effectName);
        GUI.color = color; 

        templateGo = EditorGUILayout.ObjectField("Prefab", templateGo, typeof(GameObject), true, GUILayout.MaxHeight(20)) as GameObject;
        // 理论上轨道不允许空值，若给空值就不管
        if (!templateGo)
        {
            EditorGUILayout.HelpBox("请选择特效预设", MessageType.Error);
            return;
        }
        ReplaceEffectGo();

        postProcessClip.dummy = EditorGUILayout.IntField("Dummy", postProcessClip.dummy);
        postProcessClip.shifting = EditorGUILayout.Vector3Field("Shifting", postProcessClip.shifting);
        postProcessClip.loop = EditorGUILayout.Toggle("Loop", postProcessClip.loop);
        // postProcessClip.followType = (EVFXSpace)EditorGUILayout.EnumPopup("Follow Type", postProcessClip.followType);
        postProcessClip.defaultLength = EditorGUILayout.FloatField("Default Length", postProcessClip.defaultLength);

        EditorUtility.SetDirty(postProcessClip);
        serializedObject.ApplyModifiedProperties();
    }

    void ReplaceEffectGo()
    {
        var path = GetPrefabPath();
        if (path != postProcessClip.effectPath)
        {
            postProcessClip.SetPath(path, templateGo);
        }
    }

    string GetPrefabPath()
    {
        if (templateGo == null) return string.Empty;
        var isMainAsset = AssetDatabase.IsMainAsset(templateGo);
        if (isMainAsset)
            return AssetDatabase.GetAssetPath(templateGo);

        var prefabAsset = PrefabUtility.GetCorrespondingObjectFromOriginalSource(templateGo);
        return AssetDatabase.GetAssetPath(prefabAsset);
    }
}